package com.macro.mall.portal.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.UmsComment;
import com.macro.mall.portal.common.MallConst;
import com.macro.mall.portal.dto.AddCommentDto;
import com.macro.mall.portal.dto.CommentDto;
import com.macro.mall.portal.dto.TopicIndexDto;
import com.macro.mall.portal.dto.UserDetailDto;
import com.macro.mall.portal.service.UmsCommentService;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.portal.service.UmsReplyService;
import com.macro.mall.portal.service.UmsTopicService;
import com.macro.mall.security.service.RedisService;
import com.macro.mall.security.service.impl.RedisServiceImplExtend;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Controller
@Api(tags = "UmsCommentController", description = "评论")
    @RequestMapping("/comment")
public class  UmsCommentController {

    @Autowired
    private UmsCommentService umsCommentService;
    @Autowired
    private UmsMemberService umsMemberService;
    @Autowired
    private UmsTopicService umsTopicService;

    @Autowired
    private RedisServiceImplExtend redisServiceImplExtend;

    @Autowired
    private RedisService redisService;

    @ApiOperation("获取话题评论列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getTopicCommentList(@RequestParam(value = "topicId") Integer topicId,
                                          @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                          @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex) {
        CommonPage<CommentDto> result=new CommonPage<CommentDto>();
        List<UmsComment> commentList= umsCommentService.getTopicCommentList(topicId,pageIndex,pageSize);
        if(commentList.size()==0) return CommonResult.success(result);
        CommonPage<UmsComment> commonPage= CommonPage.restPage(commentList);
        List<Integer> parentCommentIds= commentList.stream().filter(s->s.getParentcommentid()!=0).map(UmsComment::getParentcommentid).distinct().collect(Collectors.toList());
        //获取父级评论
        List<UmsComment> parentCommentList= umsCommentService.getParentCommentList(parentCommentIds);
        List<String> userIds= commentList.stream().map(UmsComment::getUserid).distinct().collect(Collectors.toList());
        List<String> parentUserids= parentCommentList.stream().map(UmsComment::getUserid).distinct().collect(Collectors.toList());
        userIds=(List<String>)CollectionUtil.union(userIds,parentUserids);
        List<UserDetailDto> userDetailDtoList=umsMemberService.getUserDetail(userIds);
        //获取当前话题的所属用户
        String topicUserid=umsTopicService.getTopicUserid(topicId);
        List<CommentDto> commentDtoList=new ArrayList<CommentDto>();
        for (UmsComment c:commentList){
            CommentDto commentDto=new CommentDto();
            commentDto.setCommentId(c.getCommentid());
            UserDetailDto userDetailDto=userDetailDtoList.stream().filter(s->s.getUserId().equals(c.getUserid())).findAny().orElse(null);
            commentDto.setAvatorUrl(userDetailDto.getAvatorUrl());
            commentDto.setCommentAuditstatus(c.getCommentauditstatus());
            commentDto.setCommentContent(c.getCommentcontent());
            commentDto.setCommentCreatetime(c.getCommentcreatetime());
            commentDto.setNickName(userDetailDto.getNickName());
            commentDto.setTopicId(c.getTopicid());
            commentDto.setUserId(c.getUserid());
            commentDto.setGender(userDetailDto.getGender());
            commentDto.setReplyTotalcount(0);
            commentDto.setParentCommentid(c.getParentcommentid());
            if(c.getParentcommentid()!=0){
                UmsComment parentComment=parentCommentList.stream().filter(s->s.getCommentid()==c.getParentcommentid()).findAny().orElse(null);
                UserDetailDto parentUser=null;
                if(parentComment!=null) {
                    parentUser=userDetailDtoList.stream().filter(s -> s.getUserId().equals(parentComment.getUserid())).findAny().orElse(null);
                }
                commentDto.setParentUserId(parentUser==null?"":parentUser.getUserId());
                commentDto.setParentNickName(parentUser==null?"":parentUser.getNickName());
                commentDto.setParentAvatorurl(parentUser==null?"":parentUser.getAvatorUrl());
                commentDto.setParentGender(parentUser==null?0:parentUser.getGender());
                commentDto.setParentCommentcontent(parentComment==null?"":parentComment.getCommentcontent());
            }
            Long pariseCount= redisServiceImplExtend.bitCount(MallConst.RKEY_COMMENT_PARISECOUNT+c.getCommentid());
            commentDto.setCommentPraisecount(Integer.parseInt(pariseCount.toString()));
            //当前用户是否已点赞
            Integer uId=umsMemberService.getCurrentUser().getId();
            Boolean isParise= redisServiceImplExtend.getBit(MallConst.RKEY_COMMENT_PARISECOUNT+c.getCommentid(),uId);
            commentDto.setIsPraise(isParise);
            commentDto.setIsAuthor(c.getUserid().equals(topicUserid));
            commentDtoList.add(commentDto);
        }

        result.setList(commentDtoList);
        result.setPageNum(commonPage.getPageNum());
        result.setPageSize(commonPage.getPageSize());
        result.setTotal(commonPage.getTotal());
        result.setTotalPage(commonPage.getTotalPage());
        return CommonResult.success(result);
    }

    @ApiOperation("添加评论")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult addTopicComment(@RequestBody AddCommentDto commentDto) {
        String userId=umsMemberService.getCurrentUser().getUserid();
        UmsComment umsComment=new UmsComment();
        umsComment.setTopicid(commentDto.getTopicId());
        umsComment.setCommentcontent(commentDto.getCommentContent());
        umsComment.setUserid(userId);
        umsComment.setCommenttopstatus(0);
        umsComment.setCommentauditstatus(1);
        umsComment.setCommentdelstatus(0);
        umsComment.setCommentcreatetime(DateTime.now().toString());
        umsComment.setParentcommentid(commentDto.getParentCommentid()==null?0:commentDto.getParentCommentid());
        umsComment.setCommentpraisecount(0);
        umsCommentService.addTopicComment(umsComment);
        umsComment.setCommentid(umsComment.getCommentid());
        redisService.hIncr(MallConst.RKEY_COMMENT_COUNT+"COMMENT",umsComment.getCommentid().toString(),1L);
        return CommonResult.success(umsComment);
    }

    @ApiOperation("添加赞")
    @RequestMapping(value = "/parise/add", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult addParise(@RequestParam("commentId") Integer commentId) {
        Integer uId=umsMemberService.getCurrentUser().getId();
        redisServiceImplExtend.setBit(MallConst.RKEY_COMMENT_PARISECOUNT+commentId,uId,true);
        return CommonResult.success(0);
    }

    @ApiOperation("取消赞")
    @RequestMapping(value = "/parise/cancel", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult cancelParise(@RequestParam("commentId") Integer commentId) {
        Integer uId=umsMemberService.getCurrentUser().getId();
        redisServiceImplExtend.setBit(MallConst.RKEY_COMMENT_PARISECOUNT+commentId,uId,false);
        return CommonResult.success(0);
    }




}